from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, ListCreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from goods.models import SKU
from users import serializers, constants
from users.models import User
from meiduo_mall.utils.DBHelper import create_redis_conn


# GET usernames/(?P<username>\w{5,20})/count/
class UsernameCountViews(APIView):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        context = {
            "username": username,
            "count": count
        }
        return Response(context)

# GET mobiles/(?P<mobile>1[3-9]\d{9})/count/
class MobileCountViews(APIView):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        context = {
            "mobile": mobile,
            "count": count
        }
        return Response(context)


# POST /users/
class RegisterViews(CreateAPIView):
    """用户注册视图"""
    serializer_class = serializers.RegisterSerializers


# GET /user/
class UserDetailViews(RetrieveAPIView):
    """用户详情信息"""
    serializer_class = serializers.UserDetailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


# put /email/
class EmailViews(UpdateAPIView):
    """电子邮件验证"""
    permission_classes = [IsAuthenticated]
    serializer_class = serializers.EmailSerializer

    def get_object(self, *argsm, **kwargs):
        return self.request.user


# PUT /emails/verification/?token=xxx  url(r'^emails/verification/$', views.VerifyEmailView.as_view()),
class VerifyEmailView(APIView):
    """验证邮箱连接"""
    def put(self, request):
        token = request.query_params.get('token')
        if not token:
            return Response({"message": "连接无效"}, status=status.HTTP_400_BAD_REQUEST)
        user = User.check_verify_email_token(token)
        if user is None:
            return Response({"message": "连接信息无效"}, status.HTTP_400_BAD_REQUEST)
        else:
            user.email_active = True
            user.save()
            return Response({"message": "OK"})


class AddressViewsSet(ModelViewSet):
    serializer_class = serializers.AddressSerializers
    permission_classes = [IsAuthenticated]
    
    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 3,
            'addresses': serializer.data,
        })

    def create(self, request, *args, **kwargs):
        quertset = self.get_queryset()
        count = quertset.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({"message": "添加的地址数量超额"}, status=status.HTTP_400_BAD_REQUEST)
        return super(AddressViewsSet, self).create(request)
    
    # def destroy(self, request, pk):
    def destroy(self, request, *args, **kwargs):
        # queryset = Address.objects.filter(user=request.user).filter(id)
        # address = Address.objects.filter(user=request.user).filter(id=pk)[0]
        address = self.get_object()
        address.is_deleted = True
        address.save()
        return Response(status=status.HTTP_204_NO_CONTENT)

    def update(self, request, *args, **kwargs):
        address = self.get_object()
        serializer = serializers.AddressSerializers(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    @action(methods=['put'], detail=True)
    def status(self, request, pk):
        address = self.get_object()
        print(address.id)
        request.user.default_address = address
        request.user.save()
        return Response({"message": "OK"}, status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True)
    def title(self, request, pk):
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"message": "OK"}, status=status.HTTP_200_OK)


class UserBrowsingHistoryView(CreateAPIView):
    serializer_class = serializers.AddUserBrowsingHistorySerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user_id = request.user.id
        print(user_id)
        redis_conn = create_redis_conn('history')
        sku_list = redis_conn.lrange('history_%s' % user_id, 0, -1)
        print(sku_list)
        sku_id_list = []
        for sku_id in sku_list:
            sku = SKU.objects.get(id=sku_id)
            sku_id_list.append(sku)
        serializer = serializers.SKUSerializer(sku_id_list, many=True)

        return Response(serializer.data)
